﻿package smooth.core.object.flickrComponent {
	import app.core.action.RotatableScalable;
	import app.core.object.ImageObject;
	import smooth.core.canvas.multimediaCanvas.MultimediaCanvas;
	import smooth.core.object.flickrImageComponent.FlickrImageComponent;
	import caurina.transitions.Tweener;
	import flash.display.DisplayObject;		
	import flash.display.MovieClip;	
	import flash.display.Sprite;	
	import flash.events.Event;	
	import flash.events.MouseEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLVariables;
	import flash.geom.Point;
	import smooth.core.object.flickrUserComponent.FlickrUserObject;
	import smooth.core.object.flickrComponent.FlickrPhotoInfosLoadedEvent;
	import smooth.core.object.flickrComponent.FlickrSearchCompletedEvent;
	import smooth.core.object.localizationComponent.LocalizationComponent;
	
		
	public class FlickrLoader extends Sprite {
		private var index:int = 0;		
		private var rest:URLLoader = null;
		// START - 20081123 - LSA
		private var restGetInfoPhotos:URLLoader = null;
		private var restGetInfoLocation:URLLoader = null;
		// END - 20081123 - LSA
		private var flickr:XML = null;
		private var flickrComponent:FlickrComponent;
		private var fetchCount:Number;
		private var allPics:Array;	
		private var requestLabel:String;
		public var photo:FlickrImageComponent;
		private static var FLICKR_URL_API:String = "http://api.flickr.com/services/rest/";
		private static var FLICKR_KEY_API:String = "566c6aa058a2b4aa13f1b6ddc9bfd582";
		private static var FLICKR_URL_PHOTOS:String = "http://static.flickr.com/";
		private static var FLICKR_METHOD_RECENT:String = "flickr.photos.getRecent";
		private static var FLICKR_METHOD_SEARCH:String = "flickr.photos.search";
		// START - 20081123 - LSA
		private static var FLICKR_METHOD_GET_INFO:String = "flickr.photos.getInfo";
		private static var FLICKR_METHOD_GET_LOCATION:String = "flickr.photos.geo.getLocation";
		// END - 20081123 - LSA
		private static var FLICKR_PER_PAGE:Number = 50;
		
		// START - 20081123 - LSA
		//public function FlickrLoader(d:FlickrComponent, fetchIn:Number) {
		public function FlickrLoader(d:FlickrComponent = null, fetchIn:Number = 20) {
			flickrComponent = d;
			fetchCount = fetchIn;
			allPics = new Array();
		}
		
		public function searchText(searchText:String = ""):void {			
			doClearPics();
			this.requestLabel = searchText;
			var request:URLRequest = new URLRequest(FLICKR_URL_API);
			var variables:URLVariables = new URLVariables();
			variables.api_key = FLICKR_KEY_API;
			variables.method = FLICKR_METHOD_SEARCH;
			variables.media = "photos"; 
			variables.text = searchText;
			request.data = variables;
			rest = new URLLoader();
			rest.addEventListener("complete", doParse , false, 0, true);
			// START - 20081123 - LSA
			//flickrComponent.doAnimationFadeOut();
			// END - 20081123 - LSA
			rest.load(request);
		}
		
		// START - 20081121 - LSA
		//public function searchGeoLocal(lat:Number, lng:Number):void {			
		public function searchGeoLocal(lat:Number, lng:Number, distance:Number = 5):void {
		// END - 20081121 - LSA
			doClearPics();
			// START - 20081126 - LSA
			//this.requestLabel = "Lat:" + lat + " / Lng:" + lng;
			this.requestLabel = "Lat:" + lat.toFixed(3) + " / Lng:" + lng.toFixed(3);
			// END - 20081126 - LSA
			var request:URLRequest = new URLRequest(FLICKR_URL_API);
			var variables:URLVariables = new URLVariables();
			variables.api_key = FLICKR_KEY_API;
			variables.method = FLICKR_METHOD_SEARCH;
			variables.media = "photos"; 
			variables.has_geo = true;
			variables.lat = lat;
			variables.lon = lng;
			// START - 20081121 - LSA
			//variables.radius = "5";
			variables.radius = distance;
			// END - 20081121 - LSA
			variables.radius_units = "km";
			variables.per_page = FLICKR_PER_PAGE;
			request.data = variables;
			rest = new URLLoader();
			rest.addEventListener("complete", doParse , false, 0, true);
			// START - 20081123 - LSA
			//flickrComponent.doAnimationFadeOut();
			// END - 20081123 - LSA
			rest.load(request);
		}
		
		// START - 20081123 - LSA
		public function searchUserPhotosByNsid(nsid:String, username:String):void {
			if (nsid != "") {
				doClearPics();
				this.requestLabel = username+"'s photos";
				var request:URLRequest = new URLRequest(FLICKR_URL_API);
				var variables:URLVariables = new URLVariables();
				variables.api_key = FLICKR_KEY_API;
				variables.method = FLICKR_METHOD_SEARCH;
				variables.media = "photos"; 
				variables.user_id = nsid;
				variables.per_page = FLICKR_PER_PAGE;
				request.data = variables;
				rest = new URLLoader();
				rest.addEventListener("complete", doParse , false, 0, true);
				rest.load(request);
			}
		}
		
		public function searchPhotosTakenOnDate(after:Date, before:Date=null):void {
			if (after != null) {
				doClearPics();
				if (before == null) {
					after = new Date(after.getFullYear(), after.getMonth(), after.getDate(), 0, 0, 0, 0);
					before = new Date(after.getTime() + (1000 * 60 * 60 * 24));
					this.requestLabel = "Photos taken on " + before.toDateString();
				} else {
					this.requestLabel = "Photos taken between "+after.toDateString()+" "+after.toTimeString()+" and "+before.toDateString()+" "+before.toTimeString();
				}
				var request:URLRequest = new URLRequest(FLICKR_URL_API);
				var variables:URLVariables = new URLVariables();
				variables.api_key = FLICKR_KEY_API;
				variables.method = FLICKR_METHOD_SEARCH;
				variables.media = "photos"; 
				variables.min_taken_date = after.getFullYear().toString() + "-" + after.getMonth().toString() + "-" + after.getDate().toString()+ " " +
										after.getHours().toString()+":"+after.getMinutes().toString()+":"+after.getSeconds().toString();
				variables.maxn_taken_date = before.getFullYear().toString() + "-" + before.getMonth().toString() + "-" + before.getDate().toString()+ " " +
										before.getHours().toString()+":"+before.getMinutes().toString()+":"+before.getSeconds().toString();
				variables.per_page = FLICKR_PER_PAGE;
				request.data = variables;
				rest = new URLLoader();
				rest.addEventListener("complete", doParse , false, 0, true);
				rest.load(request);
			}
		}
		
		public function getPhotoInfos(photoId:String, flickrImageObject:FlickrImageObject):void {
			if (photoId != null) {
				var request:URLRequest = new URLRequest(FLICKR_URL_API);
				var variables:URLVariables = new URLVariables();
				variables.api_key = FLICKR_KEY_API;
				variables.method = FLICKR_METHOD_GET_INFO;
				variables.photo_id = photoId;
				if (flickrImageObject != null)
					variables.secret = flickrImageObject.getSecret();
				request.data = variables;
				this.restGetInfoPhotos = new URLLoader();
				this.restGetInfoPhotos.addEventListener("complete", doParseGetPhotoInfos , false, 0, true);
				this.restGetInfoPhotos.load(request);
			}
		}
		
		public function getPhotoLocation(photoId:String):void {
			if (photoId != null) {
				var request:URLRequest = new URLRequest(FLICKR_URL_API);
				var variables:URLVariables = new URLVariables();
				variables.api_key = FLICKR_KEY_API;
				variables.method = FLICKR_METHOD_GET_LOCATION;
				variables.photo_id = photoId;
				request.data = variables;
				this.restGetInfoLocation = new URLLoader();
				this.restGetInfoLocation.addEventListener("complete", doParseGetPhotoLocation , false, 0, true);
				this.restGetInfoLocation.load(request);
			}
		}
		// END - 20081123 - LSA
		
		public function getRecent():void {			
			doClearPics();
			var request:URLRequest = new URLRequest(FLICKR_URL_API);
			var variables:URLVariables = new URLVariables();
			variables.api_key = FLICKR_KEY_API;
			variables.method = FLICKR_METHOD_RECENT;
			request.data = variables;
			rest = new URLLoader();
			rest.addEventListener("complete", doParse , false, 0, true);
			rest.load(request);
		}
		
		private function doParse(event:Event):void {			
			this.flickr = new XML(rest.data);
			this.doDisplayPhotos();
		}

		private function doDisplayPhotos():void {
			var id:String = null;
			var secret:String = null;
			var server:String = null;			
			var url:String = null;
			var request:URLRequest = null;			
			
			var len:int = flickr..photo.length();
			
			if (len > 0) {
				var size:int = 600;
				var posX:int = (this.flickrComponent.stage.stageWidth-size)/2;
				var posY:int = (this.flickrComponent.stage.stageHeight - size) / 2;
				// START - 20081129 - LSA
				//var canvas1:MultimediaCanvas = new MultimediaCanvas(this.requestLabel, posX, posY, size, size, 0xFFFFFF);
				var canvas1:MultimediaCanvas = new MultimediaCanvas(this.requestLabel, posX, posY, size, size, 0x0000FF);
				// END - 20081129 - LSA
				flickrComponent.parent.addChild(canvas1);
				canvas1.doAnimationFadeIn();
				
				if(len > fetchCount)
					len = fetchCount;
				
				for(var i:int=0; i<len; i++) {
					server = flickr..photo[i].@server.toString();
					id = flickr..photo[i].@id.toString();
					secret = flickr..photo[i].@secret.toString();
					var imageObject:FlickrImageObject = new FlickrImageObject(server, id, secret);
					photo = new FlickrImageComponent("photo_"+i, imageObject, canvas1.width/2, canvas1.height/2, 0.5, true, false, true, false);
					canvas1.pushMultimediaObject(photo);
					allPics.push(photo);
					photo.doAnimationFadeIn(canvas1.width, canvas1.height);
				}
				// START - 20081123 - LSA
				//flickrComponent.doAnimationFadeIn();
				//flickrComponent.doInitSearchLabel("");
				this.dispatchEvent(new FlickrSearchCompletedEvent(""));
				// END - 20081123 - LSA
			} else {
				trace("No photo returned by flicker");
				// START - 20081123 - LSA
				//flickrComponent.doAnimationFadeIn();
				//flickrComponent.doInitSearchLabel("No photo found");
				this.dispatchEvent(new FlickrSearchCompletedEvent("No photo found"));
				// END - 20081123 - LSA
			}
		}
		
		// START - 20081123 - LSA
		private function doParseGetPhotoInfos(event:Event):void {	
			var photoInfosXML:XML = new XML(this.restGetInfoPhotos.data);
			var len:int = photoInfosXML.photo.length();
			if (len > 0) {
				var nsid:String = photoInfosXML.photo.owner.@nsid.toString();
				var username:String = photoInfosXML.photo.owner.@username.toString();
				var realname:String = photoInfosXML.photo.owner.@realname.toString();
				var location:String = photoInfosXML.photo.owner.@location.toString();
				var title:String = photoInfosXML.photo.title.toString();
				var description:String = photoInfosXML.photo.description.toString();
				var takenDate:String = photoInfosXML.photo.dates.@taken.toString();
				
				var flickrUserObject1:FlickrUserObject = new FlickrUserObject();
				flickrUserObject1.setNsid(nsid);
				flickrUserObject1.setUsername(username);
				flickrUserObject1.setRealname(realname);
				flickrUserObject1.setLocation(location);
				
				var flickrImageMetaData1:FlickrImageMetadataObject = new FlickrImageMetadataObject();
				flickrImageMetaData1.setTitle(title);
				flickrImageMetaData1.setDescription(description);
				flickrImageMetaData1.setTakenDate(takenDate);
				
				this.dispatchEvent(new FlickrPhotoInfosLoadedEvent(flickrUserObject1, flickrImageMetaData1));
			}
		}	
		private function doParseGetPhotoLocation(event:Event):void {	
			var photoInfosXML:XML = new XML(this.restGetInfoLocation.data);
			trace(photoInfosXML);
			var len:int = photoInfosXML.photo.length();
			if (len > 0) {
				var lat:String = photoInfosXML.photo.location.@latitude.toString();
				var lng:String = photoInfosXML.photo.location.@longitude.toString();
				var neighbourhood:String = photoInfosXML.photo.location.neighbourhood.toString();
				var neighbourhoodId:String = photoInfosXML.photo.location.neighbourhood.@place_id.toString();
				var locality:String = photoInfosXML.photo.location.locality.toString();
				var localityId:String = photoInfosXML.photo.location.locality.@place_id.toString();
				var country:String = photoInfosXML.photo.location.country.toString();
				var countryId:String = photoInfosXML.photo.location.country.@place_id.toString();
				var flickrLocalizationObject1:FlickrLocalizationObject = new FlickrLocalizationObject();
				flickrLocalizationObject1.setLat(Number(lat));
				flickrLocalizationObject1.setLng(Number(lng));
				flickrLocalizationObject1.setNeighbourhood(neighbourhood);
				flickrLocalizationObject1.setNeighbourhoodId(neighbourhoodId);
				flickrLocalizationObject1.setLocality(locality);
				flickrLocalizationObject1.setLocalityId(localityId);
				flickrLocalizationObject1.setCountry(country);
				flickrLocalizationObject1.setCountryId(countryId);
				
				this.dispatchEvent(new FlickrPhotoLocationLoadedEvent(flickrLocalizationObject1));
			}
		}
		// END - 20081123 - LSA
		
		private function doClearPics():void {
			allPics = new Array();
		}

		public static function getPhotoUrl(imageObject:FlickrImageObject):String {
			return FLICKR_URL_PHOTOS + imageObject.getServer() + "/" + imageObject.getId() + "_" + imageObject.getSecret() + ".jpg";
		}
		
	}
	
}